package com.ruoyi.wms.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.wms.domain.bo.DateRangeOrderCountBo;
import com.ruoyi.wms.service.InventoryService;
import com.ruoyi.wms.service.ReceiptOrderService;
import com.ruoyi.wms.service.ShipmentOrderService;
import com.ruoyi.wms.strategy.OrderTrendStrategy;
import com.ruoyi.wms.util.TimeRangeUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/dashBoard")
public class DashBoardController {
    private final ReceiptOrderService receiptOrderService;
    private final ShipmentOrderService shipmentOrderService;
    private final InventoryService inventoryService;
    // 注入所有策略实现
    private final List<OrderTrendStrategy> orderTrendStrategies;

    /**
     * 首页不同入库类型的未入库单数量
     * @return
     */
    @GetMapping("/receiptOrder/statistics")
    public R<List<Map<Integer, Integer>>> receiptOrderStatistics() {
        return R.ok(receiptOrderService.queryUnfinishedReceiptsCount());
    }

    /**
     * 首页不同出库类型的未出库单数量
     * @return
     */
    @GetMapping("/shipmentOrder/statistics")
    public R<List<Map<Integer, Integer>>> shipmentOrderStatistics() {
        return R.ok(shipmentOrderService.queryUnfinishedShipmentsCount());
    }

    /**
     * 查询各仓库货物统计
     */
    @GetMapping("/inventory/statistics")
    public R<List<Object>> queryWarehouseInventoryStatistics() {
        return R.ok(inventoryService.queryWarehouseInventoryStatistics());
    }

    /**
     * 查询时间范围内出入移库单统计
     */
    @PostMapping("/inAndOutOrder/trend")
    public R<List<Map<LocalDateTime, Integer>>> inAndOutOrderTrend(@Validated @RequestBody DateRangeOrderCountBo dateRangeOrderCountBo) {
        try {
            LocalDateTime date = dateRangeOrderCountBo.getDate();
            Integer granularity = dateRangeOrderCountBo.getGranularity();
            Integer orderType = dateRangeOrderCountBo.getOrderType();
            Integer optType = dateRangeOrderCountBo.getOptType();
            Integer orderStatus = dateRangeOrderCountBo.getOrderStatus();

            // 查找支持的策略
            OrderTrendStrategy strategy = orderTrendStrategies.stream()
                .filter(s -> s.supports(orderType))
                .findFirst()
                .orElseThrow(() -> new ServiceException("不支持的订单类型: " + orderType));

            // 执行策略
            List<Map<LocalDateTime, Integer>> result = strategy.queryTrend(date, granularity, optType, orderStatus);
            return R.ok(result);
        } catch (ServiceException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail("查询失败: " + e.getMessage());
        }
    }
}
